package allSort;

/**
 * 给定链表的头结点 head ，请将其按 升序 排列并返回 排序后的链表 。
 */
public class no77 {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode fast = head.next;
        ListNode slow = head;
        while (fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        // 排序右侧链表
        ListNode right = sortList(slow.next);
        slow.next = null;
        // 排序左侧链表
        ListNode left = sortList(head);
        // 合并两个链表并返回头结点
        ListNode node = merge(left,right);
        return node;
    }
    public static ListNode merge(ListNode l1,ListNode l2){
        if (l1 == l2){
            return l1;
        }
        if (l1 == null){
            return l2;
        }
        if (l2 == null){
            return l1;
        }
        ListNode newNode = new ListNode(-1);
        ListNode cur = newNode;
        while (l1 != null && l2 != null){
            if (l1.val <= l2.val){
                cur.next = l1;
                l1 = l1.next;
                cur = cur.next;
            }else{
                cur.next = l2;
                l2 = l2.next;
                cur = cur.next;
            }
        }
        if (l1 == null){
            cur.next = l2;
        }
        if (l2 == null){
            cur.next = l1;
        }
        return newNode.next;
    }
}
